

function stretchElements(list){
	$.each(list,function(i, n){
		var parent_width = $("#" + n).parent().width() - 4;
		parent_width = parent_width + "px";
		$("#" + n).width(parent_width);
	});
}


function clearElements(){
	//reset all textboxes
	$(":input:not(input[type='button']):not(input[type='hidden']):not(input[id='dob']):not(select[id='elder'])").val("");
	$(":checkbox").removeAttr('checked');
}


//pauls function.  Works Great!
function validDate(date){
	//var for required element error message.
	var date_message = " <span id='error_message'>Must be a valid date.</span>";
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//pauls date validator in action with jquery.
	var validator = new pdv();
	if (date.value.length > 0) {
		if (validator.IsSQLServerDate(date.value)){
			date.value = validator.DisplayDate(date.value, 'mm/dd/yyyy');
		}else{		
			$("#error").show();
			$("#" + date.id + " ~ img").after(date_message);
			$("#" + date.id).addClass('textbox_error');	
		}
	}	
}



function validateElements(list){
	//sets error count to zero, if greater then zero, some data is not valid
	var error_count = 0;
	
	//var for required element error message.
	var require_message = " <span id='error_message'>Field is required.</span>";
	
	//var for required if something is checked.
	var require_if_message = " <span id='error_message'>Field is required, if another field is checked</span>";
	
	//these fields are require on form.
	var required_fields = [];
	
	//these fields are require on form.
	var required_if_fields = {
		'Chore': ['ChoreTimeIn','ChoreTimeOut'],
		'DayOfCare': ['DayOfCareTimeIn','DayOfCareTimeOut'],
		'TTCM': ['TTCMTimeIn','TTCMTimeOut']
	};
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//if fields in the required_fields variable are empty this error is triggered.
	$.map(required_fields,function(field){
		if( !$("#" + field).val() )	{
			error_count++;
			$("#error").show();
			$("#" + field).after(require_message);
			$("#" + field).addClass('textbox_error');
		}
	});
	
	//if fields in the required_if_fields variable are empty this error is triggered.
	$.each(required_if_fields,function(i, field){
		if( $("#" + i).attr('checked') ){
			if ( i == 'TTCM' && $("#TTCMType").val() == 'PhoneCall' ){
				
			}else{
							
				if( !$("#" + field[0]).val() )	{
					error_count++;
					$("#error").show();
					$("#" + field[0]).after(require_message);
					$("#" + field[0]).addClass('textbox_error');
				}
				if( !$("#" + field[1]).val() )	{
					error_count++;
					$("#error").show();
					$("#" + field[1]).after(require_message);
					$("#" + field[1]).addClass('textbox_error');
				}			
			}
		}
	});
		
		
	//if no errors in validation, well... the data is valid!
	if(error_count){return false;}else{return true;}
}



function loadElder(){
	//takes value of selected option in the elder dropdown and passes it to the function that fills the form.
	if($("#elder option:selected").val() != -1){			
		window.location.href="dailyprogressnote.cfm?ElderID=" + $("#elder option:selected").val();
		
		//setting session variable that holds current elder selected
		var session_elder_id = new sse();
		session_elder_id.funcSetSessionElderID( $("#elder option:selected").val() );			
	}
	else{	
		window.location.href="dailyprogressnote.cfm?ElderID=" + $("#elder option:selected").val() + 
			"&DailyProgressNoteID=-1";
		var session_elder_id = new sse();
		session_elder_id.funcSetSessionElderID( $("#elder option:selected").val() );		
	}	
}


function bindElements(){
	//calls the stretch element function
	stretchElements(["Comments","FollowUp", "ScheduledAppointments", "Referral", "Other"]);
	
	//binds change event to getDataById.  This is to populate form data.
	$("#elder").bind("change", function(){
		loadElder();
	});
	
	//make meal_date textbox a datepicker
	$("#NoteDate, #ElderSignatureDate:not(input[type='hidden']), #StaffSignatureDate:not(input[type='hidden']), #SupervisorSignatureDate:not(input[type='hidden'])").datepicker({ 
		dateFormat: 'mm/dd/yy', changeYear: true, changeMonth: true, yearRange: '1900:2010', autoSize: true,
		prevText: 'Earlier', nextText: 'Later', showOn: 'button', 
		buttonImage: '/CFIDE/scripts/ajax/resources/cf/images/DateChooser.png', buttonImageOnly: true,
		onClose: function(dateText, inst) { $(this).focus()}
	});
	
	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#new_note").bind("click", function(){
		if ( validateElements() ){
			if( $("#progress_notes option:selected").val() == '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=add_progress_note', 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	
	//this binds 'edit' button's click event to trigger form validation before sending to database.  
	$("#edit_note").bind("click", function(){
		if ( validateElements() ){
			if( $("#progress_notes option:selected").val() != '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=edit_daily_progress_note', 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	
	//this binds 'delete' button's click event to trigger form validation before sending to database.  
	$("#delete_note").bind("click", function(){
		if ( validateElements() ){
			if( $("#progress_notes option:selected").val() != '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=delete_progress_note_by_id&id=' + 
								  	$("#progress_notes option:selected").val(), 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	//bind progress_notes drop down to load that progress notes data
	$("#progress_notes").bind('change', function(){
		//fillForm ( getDataById('get_progressnote_by_id', $("#progress_notes option:selected").val() ).DATA );
		window.location.href="dailyprogressnote.cfm?ElderID=" + $("#elder option:selected").val() + 
			"&DailyProgressNoteID=" + $("#progress_notes option:selected").val();
	});
	
	//adds a TimePicker to listed fields
	$("#ChoreTimeIn, #ChoreTimeOut, #DayOfCareTimeIn, #DayOfCareTimeOut, #TTCMTimeIn, #TTCMTimeOut, " + 
	  "#TimeFirstPickup ,#TimeFirstDropOff, #TimeSecondPickup, #TimeSecondDropOff, " + 
	  "#InHomeVisitTimeIn, #InHomeVisitTimeOut, #GroupVisitTimeIn, #GroupVisitTimeOut, " + 
	  "#OffSiteVisitTimeIn, #OffSiteVisitTimeOut").bind('click', function(){
		showTimePicker(this.id.replace(/Clear/g, ""));
		return false;
	});
	
	unbilledUnits();
	
	
	if( $("#progress_notes option:selected").val() == -1 ){
		$("#new_note").show();
		$("#edit_note").hide();
		$("#delete_note").hide();
	}else{
		$("#new_note").hide();
		$("#edit_note").show();
		$("#delete_note").show();
	}
}


function showTimePicker(ele){
	$("#timePicker_" + ele).remove();
	
	var proto_time_hrs = "<select id='tph_" + ele + "' style='font-size:9px;'>" + 
		"<option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option>" + 
		"<option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option>" + 
		"<option value='9'>9</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option>" +
		"</select>";
		
	var proto_time_min = "<select id='tpm_" + ele + "' style='font-size:9px;'>" + 
		"<option value='00'>00</option><option value='15'>15</option><option value='30'>30</option><option value='45'>45</option>" + 
		"</select>";
		
	var proto_time_suffix = "<select id='tps_" + ele + "' style='font-size:9px;'>" + 
		"<option value='-1'> </option><option value='AM'>AM</option><option value='PM'>PM</option>" + 
		"</select> <span id='clearTimePicker_"+ele+"'>X</span>";
		
	$("#" + ele).before("<div id='timePicker_" + ele + "'>" + proto_time_hrs + " " + proto_time_min + " " + proto_time_suffix + "</div>");
	
	$("#clearTimePicker_" + ele).bind("click", function(){
		$("#timePicker_" + ele).remove();				   
	});
	
	$("#tps_" + ele).bind("change", function(){
		$("#" + ele).val( $("#tph_"+ele).val() + ":" + $("#tpm_"+ele).val() + " " + $("#tps_"+ele).val() );
		$("#timePicker_" + ele).remove();
		$("#" + ele).trigger('change');
	});	
}


function unbilledUnits(){
	$("#ChoreTimeIn, #ChoreTimeOut").bind('change', function(){
		try {
			$("#UnbilledChoreUnits").val( calcUnbilledUnits( $("#ChoreTimeIn").val(), $("#ChoreTimeOut").val()) );
		}catch(err){}		
	});
	
	$("#DayOfCareTimeIn, #DayOfCareTimeOut").bind('change', function(){
		$("#UnbilledDayOfCareUnits").val( calcUnbilledUnits( $("#DayOfCareTimeIn").val(), $("#DayOfCareTimeOut").val()) );
	});
	
	$("#TTCMTimeIn, #TTCMTimeOut").bind('change', function(){
		$("#UnbilledTTCMUnits").val( 1 );
	});
}


function calcUnbilledUnits(tin, tout){
	var tc = new EvalTime();
	return tc.funcCompareTime(tin, tout);
}


function submitForm(obj, api){
	//ajax POST to add a provider to database.
	$.ajax({
		type:'POST', url:'api.cfm?api=' + api, dataType: 'json', async: true, data: obj,
		success: function() {return true;},
		complete: function(){
			clearElements();
			return true;
		},
		error: function(){return false;}
	});
}


//ajax GET to retrive data from database.
var getDataById = function(api, id){
	
	var data = {};
	
	var api_url = "api.cfm?api=" + api + ( (id) ? "&id=" + id : "" );	
	
	if (id != -1){
		$.ajax({
		type:'GET', url: api_url, dataType: 'json', async: false,
			success: function(json) { data = json; },
			complete: function() {  },
			error: function() {  }
		});
	}	
	return data;
};


$(function(){
	bindElements();		
	
   
});